import {
    Inject, Controller, Post, Get,
    Body, Query
} from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { DishService } from '../service/dish.service';
import { Dish } from '../entity/dish.entity';

@Controller('/dish')
export class DishController {
    @Inject()
    ctx: Context;

    @Inject()
    dishService: DishService;

    @Post('/create')
    async create(@Body() dish: Partial<Dish>) {
        try {
            const result = await this.dishService.create(dish);
            return {
                code: 200,
                message: '创建成功',
                data: result
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '创建失败'
            };
        }
    }

    @Post('/update')
    async update(@Body() dish: Partial<Dish>) {
        try {
            const success = await this.dishService.update(dish.id, dish);
            return {
                code: 200,
                message: success ? '更新成功' : '更新失败'
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '更新失败'
            };
        }
    }

    @Get('/del')
    async delete(@Query('id') id: number,) {
        try {
            const success = await this.dishService.delete(id);
            return {
                code: 200,
                message: success ? '删除成功' : '删除失败'
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '删除失败'
            };
        }
    }

    @Get('/detail')
    async getInfo(@Query('id') id: number) {
        try {
            const dish = await this.dishService.getInfo(id);
            return {
                code: 200,
                message: '获取成功',
                data: dish
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '获取失败'
            };
        }
    }

    @Get('/list')
    async getList(
        @Query('page') page: number,
        @Query('pageSize') pageSize: number,
        @Query('dishName') dishName?: string,
        @Query('status') status?: number,
        @Query('categoryId') categoryId?: number
    ) {
        try {
            const [list, total] = await this.dishService.getList({
                page,
                pageSize,
                dishName,
                status,
                categoryId
            });

            return {
                code: 200,
                message: '获取成功',
                data: list,
                total
            };
        } catch (error) {
            return {
                code: 500,
                message: error.message || '获取失败'
            };
        }
    }
}